﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MICZ.CodeBuilder.Commons.JwtExtensions;
using MICZ.CodeBuilder.IService.Userinfo;
using MICZ.CodeBuilder.Service.Userinfo;
using MICZ.CodeBuilder.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MICZ.CodeBuilder.Filter.Login
{
    public class LoginFilterAttribute : ActionFilterAttribute
    {
        private readonly IUserinfoService userinfoService;
        public LoginFilterAttribute(IUserinfoService _userinfoService)
        {
             userinfoService= _userinfoService;
        }
        /// <summary>
        /// 控制器中加了该属性的方法中代码执行之前该方法。
        /// 所以可以用做权限校验。
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            // 当api发送请求，自动调用这个方法
            var request = context.HttpContext.Request; // 获取请求的请求体
            //var authorization = request.Headers.Authorization; // 获取请求的token对象
            //var authorization = HttpContext.GetTokenAsync("access_token"); // 获取请求的token对象
            var authorization = request.Headers["Authorization"]; // 获取请求的token对象
            //var token1 = JwtHelper.SerializeJWT(authorization);
            if (string.IsNullOrWhiteSpace(authorization))
            {
                ContentResult contentResult = new ContentResult();
                contentResult.ContentType = "text/html; charset=utf-8";
                contentResult.StatusCode = 0000;
                JsonDataModel jsonDataModel = new JsonDataModel();
                jsonDataModel.Status = 0;
                jsonDataModel.Msg = "登录超时或未登录";
                contentResult.Content = JsonConvert.SerializeObject(jsonDataModel);
                //contentResult.Content = "登录超时或未登录";
                context.Result = contentResult;
                return;
            }
            string area =context.RouteData.Values["area"].ToString();
            string controller = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();
            var token = JwtHelper.GetPrincipal(authorization);
            if (token)
            {
                //return "";
                MICZ.CodeBuilder.Models.Userinfo userinfo = userinfoService.Get(a => a.USERID == JwtHelper.USERID && a.ID == int.Parse(JwtHelper.ID));
                AuthContextUser.CurrentUser = userinfo;
            }
            else
            {
                //context.Result = new RedirectResult("/WebApi/Login/Error");
                ContentResult contentResult = new ContentResult();
                contentResult.ContentType = "text/html; charset=utf-8";
                contentResult.StatusCode = 0000;
                JsonDataModel jsonDataModel = new JsonDataModel();
                jsonDataModel.Status = 0;
                jsonDataModel.Msg = "登录超时或未登录";
                contentResult.Content = JsonConvert.SerializeObject(jsonDataModel);
                //contentResult.Content = "登录超时或未登录";
                context.Result = contentResult;
                return;
            }
        }
        /// <summary>
        /// 控制器中加了该属性的方法执行完成后才会来执行该方法。
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }
        /// <summary>
        /// 控制器中加了该属性的方法执行完成后才会来执行该方法。比OnActionExecuted()方法还晚执行。
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            //string sql = "INSERT INTO dbo.TInfor( Fno, Fname, Fobject, Fscore )VALUES( 'filtertest','过滤器测试','OnResultExecutionAsync','33')";
            //DBHelper.DBExecute(sql);
            return base.OnResultExecutionAsync(context, next);
        }
    }
}
